package com.server.libs.login;

import com.alibaba.fastjson2.JSON;
import com.server.libs.login.data.AppCache;
import com.server.pojo.MobileApp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.UUID;

@Slf4j
@Component
public class AppAuth {
    @Autowired
    StringRedisTemplate redis;

    String getSaveKey(String id,String token){
        String saveKey = "AppToken_{id}_{token}";
        return saveKey.replace("{id}", id).replace("{token}",token);
    }

    private AppCache getCache(String saveKey){
        String data = redis.opsForValue().get(saveKey);
        if (data==null) return null;
        AppCache cache = JSON.to(AppCache.class, data);
        String[] var = saveKey.split("_");
        cache.id = Integer.valueOf(var[1]);
        cache.auth = var[2];
        return cache;
    }

    public String save(MobileApp mobileApp){

        this.del(mobileApp);

        String auth = UUID.randomUUID().toString().replace("-", "");
        AppCache cache = new AppCache();
        cache.account = mobileApp.getAccount();
        redis.opsForValue().set(getSaveKey(mobileApp.getId().toString(),auth), JSON.toJSONString(cache));


        return auth;
    }

    public void del(MobileApp mobileApp){
        AppCache cache = get(mobileApp.getId());
        if (cache!=null) {
            String saveKey = getSaveKey(mobileApp.getId().toString(), cache.auth);
            redis.delete(saveKey);
            log.info("删除key："+saveKey);
        }
    }


    public AppCache get(String auth){
        Set<String> keys = redis.keys(getSaveKey("*",auth));
        if (keys == null || keys.isEmpty()) {
            return null;
        }
        String key = keys.iterator().next();
        return getCache(key);
    }

    public AppCache get(Integer id){
        Set<String> keys = redis.keys(getSaveKey(id.toString(),"*"));
        if (keys == null || keys.isEmpty()) {
            return null;
        }
        String key = keys.iterator().next();
        return getCache(key);
    }
}
